<template>
  <card ref="Card">
    <!-- 单号 -->
    <el-form :model="numberForm" ref="NumberForm" :rules="numberRules" label-width="140px">
      <row-col>
        <el-form-item label="单号" prop="number" class="mb-20">
          <el-input type="textarea" v-model="numberForm.number"></el-input>
        </el-form-item>
      </row-col>
    </el-form>
    <!-- 其他信息 -->
    <el-form :model="form" ref="Form" label-width="140px" :rules="rules">
      <el-form-item label="计算重量:">
        <el-input-number v-model="form.length" controls-position="right" @change="calculate" :min="0"/>
        长(cm) *
        <el-input-number v-model="form.width" controls-position="right" @change="calculate" :min="0"/>
        宽(cm) *
        <el-input-number v-model="form.height" controls-position="right" @change="calculate" :min="0"/>
        高(cm) / {{$volume}}
      </el-form-item>
      <row-col>
        <el-form-item label="重量:" prop="weight">
          <el-input v-model="form.weight"></el-input>
        </el-form-item>
        <el-form-item label="运费:" prop="freight">
          <el-input v-model="form.freight"></el-input>
        </el-form-item>
      </row-col>
      <row-col>
        <el-form-item label="内件品名:">
          <el-input v-model="form.articleName" placeholder="中文"></el-input>
        </el-form-item>
        <el-form-item label="收件人姓名:">
          <el-input v-model="form.receiverName" placeholder="中文"></el-input>
        </el-form-item>
        <el-form-item label="收件人详细地址:">
          <el-input v-model="form.receiverAddress" placeholder="中文"></el-input>
        </el-form-item>
        <el-form-item label="收件人联系电话:">
          <el-input v-model="form.receiverPhone" placeholder="中文"></el-input>
        </el-form-item>
        <el-form-item label="发往网点:">
          <search-select-all v-model="form.sendToUserId" @get="getSite"/>
        </el-form-item>
        <el-form-item label="打印时间:" v-permission="['admin']">
          <el-date-picker
            v-model="form.printTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="修改原因:" prop="reason">
          <el-input v-model="form.reason"></el-input>
        </el-form-item>
        <el-form-item slot="r">
          <el-input v-model="form.laosArticleName" placeholder="老挝语"></el-input>
        </el-form-item>
        <el-form-item slot="r">
          <el-input v-model="form.laosReceiverName" placeholder="老挝语"></el-input>
        </el-form-item>
        <el-form-item slot="r">
          <el-input v-model="form.laosReceiverAddress" placeholder="老挝语"></el-input>
        </el-form-item>
      </row-col>
    </el-form>
    <div slot="footer" v-if="hasSubmit">
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </card>
</template>

<script>
  import {validateMoney, validateNumber} from "@/utils/validate";
  import {checkApi, checkPriceApi} from "@/api/operation";
  import {addEditExpressOrderApi} from "@/api/order/edit";
  import {resetForm} from "@/utils/common";
  import SearchSelectAll from '@/views/components/SearchSelectAll'

  export default {
    name: "Edit",
    components: {SearchSelectAll},
    data() {
      return {
        hasSubmit: true,
        errorList: [],
        numberForm: {
          number: ''
        },
        numberRules: {
          number: [
            {required: true, message: '请输入单号', trigger: 'blur'},
            {validator: this.validateOrderAll, trigger: 'blur'}
          ]
        },
        form: {
          numbers: '', // 单号
          length: 0, width: 0, height: 0, // 计算
          weight: '', // 重量
          freight: '',  // 运费
          articleName: '', laosArticleName: '', // 品名
          receiverName: '', laosReceiverName: '', // 收件人姓名
          receiverAddress: '', laosReceiverAddress: '', // 收件人地址
          receiverPhone: '', // 收件人联系电话
          sendToUserId: null, sendToUserName: '', sendToName: '', laosSendToName: '', // 发往网点
          printTime: '', // 打印时间
          reason: '' // 修改原因
        },
        rules: {
          weight: {validator: validateNumber, trigger: 'blur'},
          freight: {validator: validateMoney, trigger: 'blur'},
          reason: {required: true, message: '修改原因', trigger: 'blur'}
        }
      }
    },
    mounted() {
      this.checkPrice();
    },
    methods: {
      // 提交
      submit() {
        if (!this.form.numbers) {
          this.$errorMsg('单号检测未通过，请重新输入！');
          return
        }
        this.$refs['Form'].validate((valid) => {
          if (!valid) return false;
          this.$msgBox('确认提交？').then(() => {
            let data = {...this.form};
            delete data.length;
            delete data.width;
            delete data.height;
            /* 去除空键 */
            for (let key in data) {
              if (!data[key]) delete data[key]
            }
            if (Object.keys(data).length === 2) {
              this.$errorMsg('没有修改任何东西，无法提交！')
              return
            }
            if (data.weight) data.weight = this.form.weight / 1;
            if (data.freight) data.freight = this.form.freight / 1;
            this.$startLoading();
            addEditExpressOrderApi(data).then(result => {
              this.$stopLoading()
              if (result.status !== 200) return
              this.cancel();
            }).catch(() => {
              this.$stopLoading()
            })
          });
        })
      },

      // 查询余额
      checkPrice() {
        checkPriceApi().then(result => {
          // 余额低于警戒线
          if (result.resultParam.isWarning) {
            this.hasSubmit = false;
            this.$warnMsg('余额低于警戒线，无法提交')
          }
        })
      },

      // 检测全部单号
      validateOrderAll(rule, value, callback) { // first
        value = value.trim(); // 去空
        if (value === '' || value === undefined || value == null) {
          callback(new Error('请输入单号'))
        } else {
          let list = [];
          value = value.split('\n');
          value.forEach(item => { // 去空格
            item = item.trim();
            if (item !== '') list.push(item)
          });
          for (let i = 0; i < list.length; i++) { // 去重
            for (let j = i + 1; j < list.length; j++) {
              if (list[i] === list[j]) {
                list.splice(j, 1);
                j--;
              }
            }
          }
          this.getNumbers(list.join(','))
          callback()
        }
      },

      // 获得通过单号
      getNumbers(numbers) { // second
        let param = {
          state: 4,
          numbers: numbers
        };
        this.$refs.Card.start()
        checkApi(param).then(result => {
          this.$refs.Card.stop()
          let successList = result.resultParam.successList
          let errorMap = result.resultParam.errorMap
          for (let key in errorMap) {
            if (key === 'numberNotFoundList') continue
            if (key === 'numberNotUse') continue
            successList = [...successList, ...errorMap[key]]
          }
          this.form.numbers = successList.join(',')
          this.sendErrorMsg(errorMap)
        }).catch(() => {
          this.$refs.Card.stop();
          this.form.numbers = ''
        })
      },

      // 发送错误信息
      sendErrorMsg(error) { // third
        this.errorList = [];
        const H = [];
        const h = this.$createElement;
        for (let key in error) {
          let keyName = '';
          if (key === 'numberNotArrive') continue;
          if (key === 'numberNotSender') continue
          if (key === 'numberNotDelivery') continue
          if (key === 'numberNotSign') continue
          if (key === 'numberNotFoundList') keyName = '单号不存在：';
          if (key === 'numberNotUse') keyName = '单号未使用：';
          if (key === 'numberNotIssue') continue
          if (key === 'stateReUseList') continue
          if (key === 'problemNotDeal') continue;
          if (Object.prototype.hasOwnProperty.call(error, key) && error[key].length !== 0) {
            H.push(h('p', null, `${keyName}${error[key].join(' ')}`));
            this.errorList = [...this.errorList, ...error[key]]
          }
        }
        if (H.length === 0) return
        this.$errorMsg(h('p', {style: {color: '#F56C6C'}}, H));
      },

      // 选择网点
      getSite(obj) {
        if (obj) {
          this.form.sendToUserName = obj.username;
          this.form.sendToName = obj.name;
          this.form.laosSendToName = obj.laosName;
        } else {
          this.form.sendToUserName = '';
          this.form.sendToName = '';
          this.form.laosSendToName = '';
        }
      },

      // 计算体积重量
      calculate() {
        let length = this.form.length;
        let width = this.form.width;
        let height = this.form.height;
        this.form.weight = length * width * height / this.$volume
        let weight_1 = this.form.weight.toFixed(1)
        let weight_0 = this.form.weight.toFixed(0)
        if (weight_1 / 1 === weight_0 / 1) {
          this.form.weight = weight_0
        } else {
          this.form.weight = weight_1
        }
        if (isNaN(this.form.weight)) this.form.weight = ''
      },

      // 关闭
      cancel() {
        resetForm(this, 'numberForm', 'NumberForm')
          .then(() => {
            return resetForm(this, 'form')
          })
          .then(() => {
            this.checkPrice();
            if (this.errorList.length > 0)
              this.numberForm.numbers = this.errorList.join('\n')
          })
      }
    }
  }
</script>
